import { ElNotification, ElMessage, ElLoading } from 'element-plus'
import { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
import { blobValidate } from '@/utils/common'
import axios from 'axios'
import { globalHeaders } from '@/api'
let downloadLoadingInstance: LoadingInstance
import { saveAs } from 'file-saver'
import errorCode from '@/utils/errorCode'
/**
 * @description 接收数据流生成 blob，创建链接，下载文件
 * @param {Function} api 导出表格的api方法 (必传)
 * @param {String} tempName 导出的文件名 (必传)
 * @param {Object} params 导出的参数 (默认{})
 * @param {Boolean} isNotify 是否有导出消息提示 (默认为 true)
 * @param {String} fileType 导出的文件格式 (默认为.xlsx)
 * */
export const useDownload = async (
  api: (param: any) => Promise<any>,
  tempName: string,
  params: any = {},
  isNotify: boolean = false,
  fileType: string = '.xlsx',
  fileName?: string
) => {
  if (isNotify) {
    ElNotification({
      title: '温馨提示',
      message: '如果数据庞大会导致下载缓慢哦，请您耐心等待！',
      type: 'info',
      duration: 3000
    })
  }
  const saveAsFn = (text: string | Blob, name: string | undefined, opts?: any) => {
    saveAs(text, name, opts)
  }
  const printErrMsg = async data => {
    const resText = await data.text()
    const rspObj = JSON.parse(resText)
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg)
  }
  try {
    const data = await api(params)
    const isBlob = await blobValidate(data)
    if (isBlob) {
      const blob = fileType == 'zip' ? new Blob([data], { type: 'application/zip' }) : new Blob([data])
      const name = fileType == 'zip' ? fileName : `${tempName}_${new Date().getTime()}${fileType}`
      saveAsFn(blob, name, null)
      console.log('%s ====>>>导出成功', tempName)
    } else {
      printErrMsg(data)
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('下载文件出现错误，请联系管理员！')
  }
}

const baseURL = import.meta.env.VITE_API_URL

export default {
  async oss(ossId: string | number) {
    const url = baseURL + '/resource/oss/download/' + ossId
    downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
    try {
      const res = await axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: globalHeaders()
      })
      const isBlob = blobValidate(res.data)
      if (isBlob) {
        const blob = new Blob([res.data], { type: 'application/octet-stream' })
        saveAs(blob, decodeURIComponent(res.headers['download-filename'] as string))
      } else {
        this.printErrMsg(res.data)
      }
      downloadLoadingInstance.close()
    } catch (r) {
      console.error(r)
      ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close()
    }
  },
  async localResource(resource: string) {
    let url = baseURL + '/common/download/resource?resource=' + encodeURI(resource)
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: globalHeaders()
    }).then(async res => {
      const isLogin = await blobValidate(res.data)
      if (isLogin) {
        const blob = new Blob([res.data])
        saveAs(blob, decodeURI(res.headers['download-filename']))
      } else {
        this.printErrMsg(res.data)
      }
    })
  },
  async localName(name: string, isDelete = true) {
    let url = baseURL + '/common/download?fileName=' + encodeURI(name) + '&delete=' + isDelete
    axios({
      method: 'get',
      url: url,
      responseType: 'blob',
      headers: globalHeaders()
    }).then(async res => {
      const isLogin = await blobValidate(res.data)
      if (isLogin) {
        const blob = new Blob([res.data])
        saveAs(blob, decodeURI(res.headers['download-filename']))
      } else {
        this.printErrMsg(res.data)
      }
    })
  },
  async printErrMsg(data: any) {
    const resText = await data.text()
    const rspObj = JSON.parse(resText)
    const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
    ElMessage.error(errMsg)
  },
  async zip(url: string, name: string) {
    url = baseURL + url
    downloadLoadingInstance = ElLoading.service({ text: '正在下载数据，请稍候', background: 'rgba(0, 0, 0, 0.7)' })
    try {
      const res = await axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: globalHeaders()
      })
      const isBlob = blobValidate(res.data)
      if (isBlob) {
        const blob = new Blob([res.data], { type: 'application/zip' })
        saveAs(blob, name)
      } else {
        this.printErrMsg(res.data)
      }
      downloadLoadingInstance.close()
    } catch (r) {
      console.error(r)
      ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close()
    }
  }
}
